#!/usr/bin/python
import sys
import XenAPI
import urllib2
import base64
from xml.dom.minidom import parse, parseString
path 	= "./"

tempxml  = path+"temp.xml"
temppub = path+"temppub"
tempkey =  path+"temp.key"

def read_in_xml(result):
    dom = parseString(result)
    root = dom.getElementsByTagName("xentxt:xentxtdata")
    xencert = dom.getElementsByTagName('xentxt:xencert')[0]
    xenpub  = dom.getElementsByTagName("xentxt:xenpubkey")[0]
    print xencert.firstChild.nodeValue
    print xenpub.firstChild.nodeValue
    f= open (temppub,"w")
    cert = base64.b64decode(xencert.firstChild.nodeValue)
    f.write(cert)
    f.close()
    f = open(tempkey,"w")
    key = base64.b64decode( xenpub.firstChild.nodeValue)
    f.write(key)
    f.close()


def main(session):
    host_ref = session.xenapi.session.get_this_host(session.handle)
    args = {}
    ret_val = session.xenapi.host.call_plugin(host_ref, 'xapiaik', 'main', args)
    f = open(tempxml,"w")
    f.write(ret_val);
    read_in_xml(ret_val)
    print ret_val

if __name__ == "__main__":
    if len(sys.argv) <> 4:
		print "Usage:"
		print sys.argv[0], "<XenServer host> <username> <password> "
		sys.exit(1)
    url = "https://" + sys.argv[1]
    username = sys.argv[2]
    password = sys.argv[3]
    session = XenAPI.Session(url)
    session.xenapi.login_with_password(username, password)
    try:
        main(session)
    except Exception, e:
        print str(e)
        raise

